var express = require('express');
var router = express.Router();
const pool = require('../pool.js');

//添加用户订单
// 访问地址 http://127.0.0.1:8081/order/reg
// 请求方式：post
router.post('/reg', (req, res, next) => {
	let obj = req.body;
	console.log(obj);
	pool.query('insert into ljk_order set ?', [obj], (err, result) => {
		if (err) {
			next(err);
			return;
		}
		res.send({ code: 200, msg: '插入成功', data:result});
	});
});

//删除用户订单
// 访问地址 http://127.0.0.1:8081/order/delete/:oid
// 请求方式：DELETE
router.delete('/delete/:uid', (req, res, next) => {
	let obj = req.params;
	console.log(obj);
		pool.query('delete from ljk_order where uid=?', [obj.uid], (err, result) => {
			if (err) {
				next(err);
				return;
			}
			else {
				res.send({ code: 200, msg: '删除成功' });
			}
		
	});
});


//查询用户订单
// 访问地址 http://127.0.0.1:8081/order/:user
// 请求方式：get
router.get('/:uid', (req, res, next) => {
	let obj = req.params;
	console.log(obj);
	pool.query('select * from ljk_order where uid=?', [obj.uid], (err, result) => {
		if (err) {
			next(err);
			return;
		}
		if (result.length == 0) {
			res.send({ code: 201, msg: '' });
			console.log(result);
		} else {
			res.send({ code: 200, msg: '查询成功', data: result });
			console.log(result);
		}
	});
});


//2.订单搜索(post)
//http://127.0.0.1:8888/order
router.post('/', (req, res, next) => {
	//2.1获取传递的数据
	let obj = req.body;
	console.log(obj);
	//2.2执行sql命令
	pool.query('select * from ljk_user where title like %?% ', [obj.title], (err, result) => {
		if (err) {
			next(err);
			return;
		}
		console.log(result);
		//结果是数组，如果数组长度为0说明登录失败
		if (result.length === 0) {
			res.send({ code: 201, msg: '没有相关订单' });
		} else {
			res.send({ code: 200, msg: '', data: result });
		}
	});
});

module.exports = router;